﻿using System.Collections.Generic;
using System.Linq;
using ZilLion.Service.Core.DapperWrapper;
using ZilLion.Service.Core.DapperWrapper.SqlServer;
using ZilLion.Service.ZilLionOss.Domain.Entitys;
using ZilLion.Service.ZilLionOss.Domain.Repositorys.Interface;

namespace ZilLion.Service.ZilLionOss.Domain.Repositorys
{
    public class OssRouteCacheRepositrory : SqlServerRespository<OssRouteJsonEntity>, IOssRouteCacheRepositrory

    {
        public OssRouteCacheRepositrory()
        {
            Context = new OssContext();
        }

        public OssRouteJsonEntity GetRouteJson()
        {
            return GetAll().FirstOrDefault();
        }


        public void UpdateRouteJson(OssRouteJsonEntity jsonEntity, IList<OssRouteInfoEntity> ossRouteInfos,
            UnitOfWork unit = null)
        {
            if (unit == null)
                unit = new UnitOfWork();
            using (unit)
            {
                DapperHelper.Execute("delete from oss_all_route", Context, unit);
                DapperHelper.Execute("delete from oss_route_info", Context, unit);
                DapperHelper.Execute($@"INSERT INTO dbo.oss_all_route
                                (routejson, updatetime)
                                VALUES('{jsonEntity.RouteJson}', 
                                GETDATE())", Context, unit);


                foreach (var route in ossRouteInfos)
                {
                    route.Path = route.Path ?? string.Empty;
                    route.Redirect = route.Redirect ?? string.Empty;
                    route.Name = route.Name ?? string.Empty;
                    route.Icon = route.Icon ?? string.Empty;
                    route.IsAdmin = route.IsAdmin ?? false;
                    route.IsConstant = route.IsConstant ?? false;
                    route.Nodropdown = route.Nodropdown ?? false;
                    route.Hidden = route.Hidden ?? false;
                    route.IsSystem = route.IsSystem ?? false;
                    route.Module = route.Module ?? string.Empty;
                    route.Haschild = route.Haschild ?? false;
                    DapperHelper.AddModel(route, Context,  unit);
                }
                unit.Complete();
            }
        }
    }
}